<?php

/**
 * 默认控制器
 */
class Controller_Storemanager extends Controller_Abstract
{
    function __construct($app)
    {
        parent::__construct($app);
        $this->_app = $app;
        $this->_view['store']=$this->store=Q::INI('store');
        $this->_view['roles']=$this->_app->currentUserRoles();
        if(in_array('storeadmin',$this->_view['roles'])){
            $seller=$this->_app->currentUser();
            $this->_view['sellerUser']=$seller['seller'];
        }
    }
    
    function actionIndex()
    {
        $this->_view['storeinfo']=Stores::find('store_id =?',$this->store['store_id'])->getOne();
        // 为 $this->_view 指定的值将会传递数据到视图中
		# $this->_view['text'] = 'Hello!';
    }
    
    
    /***
     *
     */         
    function actionEditInfo(){
        $this->_view['storeinfo']=Stores::find('store_id =?',$this->store['store_id'])->getOne();
        if($this->_context->isPost()){
            $va=array(
                'name'=>$this->_context->post('name'),
                'url'=>$this->_context->post('url'),
                'currency'=>$this->_context->post('currency'),
                'title'=>$this->_context->post('title'),
                'desc'=>$this->_context->post('desc'),
            );
            Helper_Array::removeEmpty($va);
            $this->_view['storeinfo']->changeProps($va);
            $this->_view['storeinfo']->save();
            //seller 
            $seller=$this->_view['storeinfo']->seller;
            if($seller){
                $seller->seller_name=$this->_context->post('seller_name');
                $seller->seller_email=$this->_context->post('seller_email');
                $seller->save();
            }
            return $this->_redirect(url('/editinfo'));
        }
//                 'domainprefix'=>$this->_context->post('domainprefix'),
//                 'domain'=>$this->_context->post('domain'),
    }
    
    function actionCategories(){
        
        $categories=Category::find('store_id=?',$this->store['store_id'])->getAll()->toArray();
        $this->_view['categories']=Helper_Array::toTree($categories, 'category_id', 'parent_id') ;
    }
    
    function actionCategoriesEdit(){
        
        $category=Category::find('store_id=? And category_id=?',$this->store['store_id'],$this->_context->query('category_id'))->getOne();
        if($this->_context->isPost()
            &&strlen($this->_context->post('name'))){
            $va=array(
                'name'=>$this->_context->post('name'),
                'code'=>$this->_context->post('code'),
                'parent_id'=>$this->_context->post('parent_id'),
            );
            if($va['parent_id']==$category->category_id
                ||$va['parent_id']==$category->parent_id){
                unset($va['parent_id']);
            }else{
                Category::checkLeavies($this->store['store_id'],$va['parent_id']);
                Category::checkLeavies($this->store['store_id'],$category->parent_id);
            }
            if($category->isNewRecord()){
                $va['store_id']=$this->store['store_id'];
            }
            Helper_Array::removeEmpty($va);
            $category->changeProps($va);
            $category->save();
            Category::checkLeavies($this->store['store_id'],$category->category_id,$category);
            return $this->_redirect(url('/categories'));
        }
        $this->_view['category']=$category;
        $this->_view['parents']=Category::find('store_id=? And parent_id=0',$this->store['store_id'])->getAll();
    }
    
    function actionTags(){
        
        $this->_view['Taggoods']=Taggoods::find('store_id=? ',$this->store['store_id'])->getAll();
    }
    
    function actionTagsEdit(){
        
//         $this->_view['categories']=Category::find('store_id=?',$this->store)->getOne();
        $tag=Taggoods::find('store_id=? And tag_id=?',$this->store['store_id'],$this->_context->query('tag_id'))->getOne();
        if($this->_context->isPost()&&
            strlen($this->_context->post('tag_name'))
        ){
            $va=array(
                'tag_name'=>$this->_context->post('tag_name'),
            );
            if($tag->isNewRecord()){
                $va['store_id']=$this->store['store_id'];
            }
            Helper_Array::removeEmpty($va);
            $tag->changeProps($va);
            $tag->save();
            return $this->_redirect(url('/tags'));
        }
        $this->_view['tag']=$tag;
    }
    
    function actionGoods(){
        $url_args['sn']=$this->_context->sn;
        $url_args['name']=$this->_context->name;
        $url_args['category_id']=$this->_context->category_id;
        $url_args['tag_id']=$this->_context->tag_id;
        if($this->_context->isPost()){
            if(strlen($this->_context->post('cmd'))){
            switch($this->_context->post('cmd')){
                case 'batchmodify':
                    
                    break;
                case 'removegoods':
                    $i=Goods::meta()->deleteWhere('goods_id in(?) And store_id=? ',$this->_context->query('goods_id'),$this->store['store_id']);
                    if($i){
                        $this->_view['success']['removegoods']=$this->_context->query('goods_id');
                    }else{
                        $this->_view['error']['removegoods']=$this->_context->query('goods_id');
                    }
                    break;
                default:break;
            }
            }
            $url_args['sn']=$this->_context->post('sn');
            $url_args['name']=$this->_context->post('name');
            $url_args['category_id']=$this->_context->post('category_id');
            $url_args['tag_id']=$this->_context->post('tag_id');
        }
        $select=Goods::find('[store_id]=? ',$this->store['store_id']);
    	if(strlen($url_args['sn'])){
        	$select->where("[sn] like ?",$url_args['sn']);
        }
   		if(strlen($url_args['name'])){
        	$select->where("[name] like ?", "%".trim($url_args['name'])."%");
        }
        if(strlen($url_args['category_id'])){
        	$select->where("[category_id] =?", $url_args['category_id']);
        }
        if(strlen($url_args['tag_id'])&&!empty($url_args['tag_id'])){
            $select->where('[tags.tag_id]=?',$url_args['tag_id']);
        }
        $select->limitPage($this->_context->query('page', 0), 15);
        $select->fetchPagination($this->_view['pager']);
        $this->_view['goods'] =$select->getAll();
        $this->_view['categories']=Helper_Array::toTree(Category::find('store_id=?',$this->store['store_id'])->getAll()->toArray(), 'category_id', 'parent_id') ;
        $this->_view['Taggoods']=Taggoods::find('store_id=? ',$this->store['store_id'])->getAll();
        $this->_view['url_args']=$url_args;
    }
    
    function actionGoodsEdit(){
        
        $goods=Goods::find('store_id=? And goods_id=?',$this->store['store_id'],$this->_context->query('goods_id'))->getOne();
        if($this->_context->isPost()){
            $addstock=$this->_context->post('addstock');
            $va=array(
                'sn'=>$this->_context->post('sn'),
                'market_price'=>$this->_context->post('market_price'),
                'price'=>$this->_context->post('price'),
                'weight'=>$this->_context->post('weight'),
                'stock'=>$this->_context->post('stock'),
                'category_id'=>$this->_context->post('category_id'),
                'imgurl_using'=>$this->_context->post('imgurl_using')
            );
            if(strlen($this->_context->post('currency'))){
                $va['currency']=$this->_context->post('currency'); 
            }else{
                $va['currency']=$this->store['currency'];
            }
            if($this->_context->post('imgurl_using')&&strlen($this->_context->post('imgurl'))>10){
                $va['imgurl']=$this->_context->post('imgurl');
            }
            // 上传图片  
            $upload_img=new Helper_Uploadimg();
            $upload_img->basepath=Q::ini('app_config/PRODUCTIMG_DIR');
            $imgReturn=$upload_img->upload($_FILES["img"],'product');
            if(strlen($imgReturn['file'])&& empty($imgReturn['error'])){
                $va['img']=$imgReturn['file'];
                $va['imgurl']=$this->_context->baseDir().Q::ini('app_config/PRODUCTIMG_BASEDIR').'/'.$va['img'];
                $upload_img->removefile($goods->img);
            }
            Helper_Array::removeEmpty($va);
            //添加 修改库存 
            if($goods->isNewRecord()){
                $va['store_id']=$this->store['store_id'];
                $va['seller_id']=$this->store['seller_id'];
                $va['stock']=$addstock;
            }else{
                if($addstock!=0){
                    $va['stock']=$goods->stock+$addstock;
				}
            }
            
            $goods->changeProps($va);
            
            $goods->tags=Taggoods::find('store_id=? And tag_id in(?)',$this->store['store_id'],$this->_context->post('tag_id'))->getAll();//$this->_context->post('tag_id');
            
            $goods->save();
            
            // 保存  多个语言的属性 
            $title=$this->_context->post('title');
            $property=$this->_context->post('property');
            $desc=$this->_context->post('desc');
            $introduction=$this->_context->post('introduction');
            
            foreach(Store_Language::all($this->store['store_id']) as $tmp_l){
		        $language=$tmp_l->language;
		
                $gld=Goods_Desc::find('goods_id=? And language=?',$goods->goods_id,$language)->getOne();
                if(empty($title[$language])) continue;
                $gld->title=$title[$language];
                $gld->desc=$desc[$language];
                $gld->introduction=$introduction[$language];
                $gld->property= Helper_Csv_Implodegoods::parseprops($property[$language]);
                if($gld->isNewRecord()){
                    $gld->goods_id=$goods->goods_id;
                    $gld->store_id=$goods->store_id;
                    $gld->language=$language;
                }
                $gld->save();
            }
            
            return $this->_redirect(url('/goods')); 
        }
        if($goods->isNewRecord()){
            $goods->imgurl = 'http://';
        }
        $this->_view['goods']=$goods;
        $this->_view['goodslangdesc']=Helper_Array::toHashmap(Goods_Desc::bylanguage($goods->goods_id)->toArray(),'language');
        $this->_view['categories']=Helper_Array::toTree(Category::find('store_id=?',$this->store['store_id'])->getAll()->toArray(), 'category_id', 'parent_id') ;
        $this->_view['Taggoods']=Taggoods::find('store_id=? ',$this->store['store_id'])->getAll();
    }
    // 批量修改 
    function actionBatchModify(){
        if(!is_array($this->_context->query('goods_id'))){
            return $this->_redirectFailureMessage('未选择商品',url('/goods'));
        }
        $select=Goods::find('[store_id]=? ',$this->store['store_id']);
        $goods=$select->where('goods_id in(?)',$this->_context->query('goods_id'))->getAll();
        if($this->_context->post('cmd')=='dobatchmodify'){
            foreach($goods as $g){
                if(strlen($this->_context->post('newcategory'))){
                    $g->category_id=$this->_context->post('newcategory');
                }
                $price=(float)$this->_context->post('price');
                $market_price=(float)$this->_context->post('market_price');
                if ($price>0&&strlen($this->_context->post('operator_price'))){
                    switch($this->_context->post('operator_price')){
                        case '=':
                            $g->price=$price;
                            break;
                        case '+':
                            $g->price=$g->price+$price;
                            break;
                        case '-':
                            $g->price=$g->price-$price;
                            break;
                        case '*':
                            $g->price=$g->price*$price;
                            break;
                        default:break;
                    }
                }
                if ($market_price>0&&strlen($this->_context->post('operator_market_price'))){
                    switch($this->_context->post('operator_market_price')){
                        case '=':
                            $g->market_price=$market_price;
                            break;
                        case '+':
                            $g->market_price=$g->market_price+$market_price;
                            break;
                        case '-':
                            $g->market_price=$g->market_price-$market_price;
                            break;
                        case '*':
                            $g->market_price=$g->market_price*$market_price;
                            break;
                        default:break;
                    }
                }
                if(strlen($this->_context->post('newtag'))){
                    $g->tags=Taggoods::find('store_id=? And tag_id in(?)',$this->store['store_id'],$this->_context->post('tag_id'))->getAll();
                }
                $g->save();
            }
            return $this->_redirectSuccessMessage(__('操作成功'),url('/goods'));
        }
        $this->_view['goods']=$goods;
        $this->_view['categories']=Category::find('store_id=?',$this->store['store_id'])->getAll();
        $this->_view['Taggoods']=Taggoods::find('store_id=? ',$this->store['store_id'])->getAll();

    }
    
    function actionOrders(){
        if($this->_context->isPost()){
            switch($this->_context->post('cmd')){
                case 'sendNotification': //执行 notification 
                    if(is_array($this->_context->post('order_id'))&&count($this->_context->post('order_id'))){
                        $nos=Orders::find('store_id=? And order_id in(?)',$this->store['store_id'],$this->_context->post('order_id'))->getAll();
                        $notification=new cmshopapi_Notification();
                        if(count($nos)){ foreach($nos as $order){
                            if($order->status_payment=='wait'){
                                $r=$notification->OrderCreated($order,$this->store['store_id']);
                            }else{
                                $r=$notification->OrderPayed($order);
                            }
                            if($r){
                                $this->_view['success']['notification'][]=$order->order_id;
                            }else{
                                $this->_view['error']['notification'][]=$order->order_id;
                            }
                        }}
                    }
                    break; 
                default: break;
            }
        }
        $select=Orders::find('store_id=? ',$this->store['store_id']);
        
        $select->limitPage($this->_context->query('page', 0), 15);
        $select->fetchPagination($this->_view['pager']);
        $this->_view['orders'] =$select->order('created DESC')->getAll();
        
        $this->_view['url_args']=array('name'=>$this->_context->query('name'));
    }
    
    function actionCustomers(){
        $this->_view['customers']=Customers::find('store_id=? ',$this->store['store_id'])->getAll();
    }
    
    /****
     * 支付
     */         
    function actionPayment(){
        $this->_view['payments']=Payment::find('')->getAll();
        $this->_view['myPayments']=Store_Payment::find('store_id=?',$this->store['store_id'])->getAll();
        $this->_view['myPaymentsArr']=Helper_Array::toHashmap($this->_view['myPayments']->toArray(),'payment_id');
        
        if($this->_context->isPost()){
            $payment=$this->_context->post('payment');
            $paymentconfig=$this->_context->post('paymentconfig');
            if(count($this->_view['myPayments'])) foreach($this->_view['myPayments'] as $mp){
                if(isset($payment[$mp->payment_id])){
                    $mp->status=1;
                    if(isset($paymentconfig[$mp->payment_id])){
                        $mp->config=$paymentconfig[$mp->payment_id];
                    }
                    $mp->save();
                    unset($payment[$mp->payment_id]);
                }else{
                    $mp->status=0;
                    $mp->save();
                }
            }
            
            if(count($payment)){
                foreach($payment as $id=>$pid){
                    $np=Store_Payment::find('store_id=? And payment_id=?',$this->store['store_id'],$pid)->getOne();
                    $np->store_id=$this->store['store_id'];
                    $np->payment_id=$pid;
                    $np->status=1;
                    if(isset($paymentconfig[$id])){
                        $np->config=$paymentconfig[$id];
                    }
                    $np->save();
                }
            }
            return $this->_redirect(url('/payment'));
//             if()
        }
    }
    
    function actionShipment(){
        $this->_view['shipments']=Store_Shipment::find('store_id=?',$this->store['store_id'])->getAll()->toArray();
        $sourceshipments=Shipment::find('status &1')->getAll()->toArray();
        $this->_view['sourceshipments']=Helper_Array::toHashmap($sourceshipments,'shipment_id'); 
    }
    
    function actionShipmentstatusmodify(){
        if(strlen($this->_context->shipment_id)){
            if(strlen($this->_context->id)<=0 && $this->_context->status){ //安装 
                $ss=Shipment::find('shipment_id=?',$this->_context->shipment_id)->getOne();
                $s=Store_Shipment::find('store_id=? And shipment_id=?',$this->store['store_id'],$this->_context->shipment_id)->getOne();
                if($s->isNewRecord()){
                    $s->store_id=$this->store['store_id'];
                    $s->shipment_id=$ss->shipment_id;
                    $s->shipment_code=$ss->shipment_code;
                    $s->title=$ss->title;
                }
                $s->config=$ss->config;
                $s->status=$this->_context->status;
                $s->save();
                $this->_redirect(url('/Shipment'));
            }
        }
        if(strlen($this->_context->id)&&strlen($this->_context->status)){
            $s=Store_Shipment::find('store_id=? And id=?',$this->store['store_id'],$this->_context->id)->getOne();
            $s->status=$this->_context->status;
            $s->save();
        }elseif($this->_context->cmd=='remove'){
            Store_Shipment::meta()->deleteWhere('store_id=? And id=?',$this->store['store_id'],$this->_context->id);
        }
        return $this->_redirect(url('/Shipment'));
    }
    
    function actionShipmentEdit(){
        $id=$this->_context->query('id');
        $this->_view['shipments']=Store_Shipment::find('store_id=?',$this->store['store_id'])->getAll();
        $this->_view['shipment']=Store_Shipment::find('store_id=? And id=?',$this->store['store_id'],$id)->getOne();
        
        if($this->_context->isPost()){
            $config=array();
            $countries=$this->_context->post('countries');
            $heavy=$this->_context->post('heavy');
            foreach($countries as $k=>$c){
                if(!(strlen($c)&&strlen($_POST['heavy'][$k]))) continue 1;
                
                $config[]=array(
                    'countries'=>$c,
                    'heavy'=>$_POST['heavy'][$k],
                    'continude'=>$_POST['continude'][$k],
                    'heavyfee'=>$_POST['heavyfee'][$k],
                    'continudefee'=>$_POST['continudefee'][$k],
                );
            }
            $this->_view['shipment']->config=$config;
            $this->_view['shipment']->title=$this->_context->post('title');
            if($this->_view['shipment']->isNewRecord()){
                $this->_view['shipment']->store_id=$this->store['store_id'];
                
            }
            $this->_view['shipment']->save();
            return $this->_redirect(url('/shipment'));
        }
    }
    
    //
    function actionSitemap(){
        $sitemap=Sitemap::find('store_id=?',$this->store['store_id'])->order('sort')->getAll();
        if($this->_context->isPost()&&count($this->_context->post('sort'))){
            $sort=$this->_context->post('sort');
            
            foreach($sitemap as $m){
                if(isset($sort[$m->id])&&strlen($sort[$m->id])){
                    $m->sort=(int)$sort[$m->id];
                    $m->save();
                }
            }
            return $this->_redirect(url('/sitemap'));
        }
        $this->_view['sitemap']=$sitemap;
    }
    
    function actionsitemapEdit(){
        $id=$this->_context->query('id');
        $this->_view['m']=Sitemap::find('store_id=? And id=?',$this->store['store_id'],$id)->getOne();
        if($this->_context->isPost()&&strlen($this->_context->query('name'))){
            if($this->_view['m']->isNewRecord()){
                $this->_view['m']->store_id=$this->store['store_id'];
            }
            $this->_view['m']->name=$this->_context->query('name');
            $this->_view['m']->url=$this->_context->query('url');
            $this->_view['m']->status=$this->_context->query('status');
            $this->_view['m']->desc=$this->_context->query('desc');
            $this->_view['m']->save();
        
            return $this->_redirect(url('/sitemap')); 
        }
    }
    
    function actionsitemapRemove(){
        $id=$this->_context->query('id');
        Sitemap::meta()->deleteWhere('store_id=? And id=?',$this->store['store_id'],$id);
        
        return $this->_redirect('storemanager/sitemap');
    }
    
    //显示登录界面
    function actionLogin(){
    	if ($this->_context->isPOST()){
    	   $seller=Sellers::find('[seller_name]=? And [store.store_id]=?',$_POST["username"],$this->store['store_id'])->query();
    	   if($seller->isNewRecord()){
              return $this->_redirect(url("storemanager/login"));
           }
           if($seller->password!=md5($_POST["password"])){
              return $this->_redirect(url("storemanager/login"));
           }
			$this->_app->changeCurrentUser(array('seller'=>$seller->toArray()),"storeadmin");
			if(strlen($this->_context->r)){
                return $this->_redirect(urldecode($this->_context->r));
            }else{
                return $this->_redirect(url("storemanager/index"));
            }
		}
		$this->_view['r']=$this->_context->query('r');
    }
    //注销
    function actionLogout(){
        $this->_app->cleanCurrentUser();
        return $this->_redirect(url("storemanager/login"));
    }
    // 更新密码 
    function actionpassword(){
        if ($this->_context->isPOST()){
           do{
                if($this->_context->post('newpassword')!=$this->_context->post('newpassword2')){
                    $this->_view['error']['newpassword2']=1;
                    break ;
                }
                if(strlen($this->_context->post('newpassword'))<=5){
                    $this->_view['error']['newpassword']=1;
                    break ;
                }
                $seller=Sellers::find('[seller_id]=? And [store.store_id]=?',$this->_view['sellerUser']['seller_id'],$this->store['store_id'])->query();
                if($seller->password!=md5($this->_context->post('oldpassword'))){
                   $this->_view['error']['oldpassword']=1;
                   break ;
                }
                $seller->password=md5($this->_context->post('newpassword'));
                $seller->save();
                $this->_view['error']['success']=1;
            }while(0);
        }
    }
    /**
     * 
     */         
    function actionNotificationEdit(){
        $this->_view['es']=Notificationevents::find()->getAll();
        $this->_view['ses']=Helper_Array::toHashmap(Store_Notificationevents::find('store_id=? ',$this->store['store_id'])->getAll()->toArray(),'event_id','status');
        if($this->_context->isPost()){
            $status=$this->_context->post('status');
            if($this->_context->post('event_id')){
                foreach($this->_context->post('event_id') as $k=>$event_id){
                    $se=Store_Notificationevents::find('store_id=? And event_id=? ',$this->store['store_id'],$event_id)->getOne();
                    if($se->isNewRecord()){
                        $se->store_id=$this->store['store_id'];
                        $se->event_id=$event_id;
                    }
                    if(isset($status[$k])){
                        $se->status=$status[$k];
                    }else{
                        $se->status=0;
                    }
                    $se->save();
                }
            }
            return $this->_redirect(url('/notificationedit'));
        }
    }
    
    function actionNotificationSet(){
        
        if($this->_context->isPost()){
            /*
            $notificationurl=urlencode($this->_context->post('notificationurl'));
            if($notificationurl!=$n->notificationurl){
                if(file_get_contents( $notificationurl,null,null,0,8)){
                    $n->urlstatus=1;
                }else{
                    $n->urlstatus=0;
                }
            }
            */
            $status=$this->_context->post('status');
            if($this->_context->post('app_id')){
                foreach($this->_context->post('app_id') as $k=>$app_id){
                    $se=Store_Notificationapps::find('store_id=? And app_id=? ',$this->store['store_id'],$app_id)->getOne();
                    if($se->isNewRecord()){
                        $se->store_id=$this->store['store_id'];
                        $se->app_id=$app_id;
                    }
                    $se->status=$status[$k];
                    $se->save();
                }
            }
        }
        $this->_view['tokens']=Token::find('store_id=?',$this->store['store_id'])->group('app_id')->getAll();
        $this->_view['n']=Helper_Array::toHashmap(Store_Notificationapps::find('store_id=?',$this->store['store_id'])->getAll()->toArray(),'app_id','status');
    }
    
    //邮件模板列表	
    function actionMailtemplateList(){
        $Mailtemplate=Store_Mailtemplate::find("[store_id]=? and useforcode=''",$this->store['store_id']);		
        $this->_view["Mailtemplate"]=$Mailtemplate->order("updated")			
            ->limitPage($this->_context->query('page',1),15)			
            ->fetchPagination($this->_view['pager'])			
            ->getAll();	
    }
        //邮件模板编辑	
    function _actionMailtemplateEdit(){		
        $usefor=$this->_context->usefor;		
        $title=$this->_context->title;		
        $content=$this->_context->content;		
        $useforcode=$this->_context->useforcode;		
        $mailtemplate_id=$this->_context->query("mailtemplate_id");		
        if($this->_context->isPOST()){			
            if(empty($title)) {				
                return $this->_redirectFailureMessage("请输入标题",url('/mailtemplateedit'));			
            }			
            if(empty($content)) {				
                return $this->_redirectFailureMessage("请输入内容",url('/mailtemplateedit'));			
            }			
            if(empty($mailtemplate_id)){				
                try{					
                    $new_Mailtemplate=new Store_Mailtemplate(array(							
                    "usefor"=>$usefor,							
                    "useforcode"=>$useforcode,							
                    "store_id"=>$this->store['store_id'],							
                    "title"=>$title,							
                    "content"=>$content						
                    ));					
                    $new_Mailtemplate->save();					
                    return $this->_redirectSuccessMessage("提交成功",url('/mailtemplatelist'));				
                }catch(QValidator_ValidateFailedException $ex){					
                    //var_dump($ex);				
                }			
            }else{				
                try{					
                    $Mailtemplate=Store_Mailtemplate::find("[Mailtemplate_id]=? and [store_id]=?",$mailtemplate_id,$this->store['store_id'])->getOne();					
                    if ($Mailtemplate->isNewRecord()){						
                        return $this->_redirectFailureMessage("请选择要修改的邮件模板",url('/mailtemplatelist'));					
                    }
                    $Mailtemplate->usefor=$usefor;					
                    $Mailtemplate->useforcode=$useforcode;					
                    $Mailtemplate->title=$title;					
                    $Mailtemplate->content=$content;					
                    $Mailtemplate->save();					
                    return $this->_redirectSuccessMessage("修改成功",url('/mailtemplatelist'));				
                }catch(QValidator_ValidateFailedException $ex){					
                    //var_dump($ex);				
                }			
            }			
            return $this->_redirectFailureMessage("修改失败",url('/mailtemplatelist'));		
        }		
        if(empty($mailtemplate_id)){			
            $Mailtemplate=new Store_Mailtemplate;			
            $Mailtemplate->usefor=$usefor;			
            $Mailtemplate->useforcode=$useforcode;			
            $this->_view["Mailtemplate"]=$Mailtemplate;		
        }else{			
            $this->_view["Mailtemplate"]=Store_Mailtemplate::find("[mailtemplate_id]=? and [store_id]=?",$mailtemplate_id,$this->store['store_id'])->getOne();		
        }	
    }
    
    //邮件模板删除	
    function actionMailtemplateDelete(){
        $mailtemplate_id=$this->_context->mailtemplate_id;		
        if (empty($mailtemplate_id)){			
            return $this->_redirectFailureMessage("请选择要删除的邮件模板",url('/mailtemplatelist'));		
        }
        $Mailtemplate=Store_Mailtemplate::find("[Mailtemplate_id]=? and [useforcode]='' and [store_id]=?",$mailtemplate_id,$this->store['store_id'])->getOne();		
        if ($Mailtemplate->isNewRecord()){			
            return $this->_redirectFailureMessage("非法操作",url('/mailtemplatelist'));		
        }
        $Mailtemplate->destroy();		
        return $this->_redirectSuccessMessage("删除成功",url('/mailtemplatelist'));	
    }
    
    function actionLanguages(){
        $store=Stores::find('store_id=?',$this->store['store_id'])->getOne();
        $this->_view['primanry']=$store->language;
        $this->_view['languages']=Store_Language::find('store_id=?',$this->store['store_id'])->getAll()->toArray();
        $sourceshipments=Language::find('status &1')->getAll()->toArray();
        $this->_view['sourceLanguages']=Helper_Array::toHashmap($sourceshipments,'language'); 
    }
    
    function actionLanguagestatusmodify(){
        if(strlen($this->_context->language)){
            if(strlen($this->_context->id)<=0 && $this->_context->status){ //安装 
                $ss=Language::find('language=?',$this->_context->language)->getOne();
                $s=Store_Language::find('store_id=? And language=?',$this->store['store_id'],$this->_context->language)->getOne();
                if($s->isNewRecord()){
                    $s->store_id=$this->store['store_id'];
                    $s->language=$ss->language;
                    $s->title=$ss->title;
                }
                $s->status=$this->_context->status;
                $s->save();
                $this->_redirect(url('/languages'));
            }
        }
        if(strlen($this->_context->id)&&strlen($this->_context->status)){
            $s=Store_Language::find('store_id=? And id=?',$this->store['store_id'],$this->_context->id)->getOne();
            $s->status=$this->_context->status;
            $s->save();
        }elseif($this->_context->cmd=='remove'){
            Store_Language::meta()->deleteWhere('store_id=? And id=?',$this->store['store_id'],$this->_context->id);
        }
        return $this->_redirect(url('/languages'));
    }
    
    function actionLanguageEdit(){
        $id=$this->_context->query('id');
        $this->_view['languages']=Store_Language::find('store_id=?',$this->store['store_id'])->getAll();
        $this->_view['language']=Store_Language::find('store_id=? And id=?',$this->store['store_id'],$id)->getOne();
        
        if($this->_context->isPost()){
            $this->_view['language']->title= $this->_context->post('title');
            $this->_view['language']->save();
            if($this->_context->post('primary')>0){
                Stores::meta()->updateWhere(array('language'=>$this->_view['language']->language),
                    'store_id=?',$this->store['store_id']);
            }
            return $this->_redirect(url('/languages'));
        }
        $store=Stores::find('store_id=?',$this->store['store_id'])->getOne();
        $this->_view['primary']=$store->language;
    }
    /**
     * 货币
     */
    function actionCurrencies(){
        $store=Stores::find('store_id=?',$this->store['store_id'])->getOne();
        $this->_view['primanry']=$store->currency;
        $this->_view['currencies']=Store_Currencies::find('store_id=?',$this->store['store_id'])->getAll()->toArray();
        $sourceshipments=Currencies::find('status &1')->getAll()->toArray();
        $this->_view['sourceCurrencies']=Helper_Array::toHashmap($sourceshipments,'code'); 
    }
    
    function actionCurrencystatusmodify(){
        if(strlen($this->_context->code)){
            if(strlen($this->_context->id)<=0 && $this->_context->status){ //安装 
                $ss=Currencies::find('code=?',$this->_context->code)->getOne();
                $s=Store_Currencies::find('store_id=? And code=?',$this->store['store_id'],$this->_context->code)->getOne();
                if($s->isNewRecord()){
                    $s->store_id=$this->store['store_id'];
                    $s->code=$ss->code;
                    $s->title=$ss->title;
                    $s->symbol_left=$ss->symbol_left;
                    $s->symbol_right=$ss->symbol_right;
                    $s->decimal_point=$ss->decimal_point;
                    $s->thousands_point=$ss->thousands_point;
                    $s->decimal_places=$ss->decimal_places;
                    $s->value=$ss->value;
                }
                $s->status=$this->_context->status;
                $s->save();
                $this->_redirect(url('/Currencies'));
            }
        }
        if(strlen($this->_context->id)&&strlen($this->_context->status)){
            $s=Store_Currencies::find('store_id=? And id=?',$this->store['store_id'],$this->_context->id)->getOne();
            $s->status=$this->_context->status;
            $s->save();
        }elseif($this->_context->cmd=='remove'){
            Store_Currencies::meta()->deleteWhere('store_id=? And id=?',$this->store['store_id'],$this->_context->id);
        }
        return $this->_redirect(url('/Currencies'));
    }
    
    function actionCurrencyEdit(){
        $id=$this->_context->query('id');
        $this->_view['currencies']=Store_Currencies::find('store_id=?',$this->store['store_id'])->getAll();
        $this->_view['currency']=Store_Currencies::find('store_id=? And id=?',$this->store['store_id'],$id)->getOne();
        
        if($this->_context->isPost()){
            do{
                $this->_view['currency']->title=$this->_context->post('title');
                $this->_view['currency']->value=(float)$this->_context->post('value');
                $this->_view['currency']->save();
                if($this->_context->post('primary')>0){
                    if($this->_view['currency']->value!=1){
                        $this->_view['error']['primary_value']=1; break;
                    }
                    Stores::meta()->updateWhere(array('currency'=>$this->_view['currency']->code),
                        'store_id=?',$this->store['store_id']);
                }
                return $this->_redirect(url('/Currencies'));
            }while(0);
        }
        $store=Stores::find('store_id=?',$this->store['store_id'])->getOne();
        $this->_view['primary']=$store->currency;
    }
    /**
     * 邮件模板 
     */
    function actionMailtemplates(){
        $this->_view['mailtemplates']=Store_Mailtemplate::find('store_id=?',$this->store['store_id'])->getAll()->toArray();
        $this->_view['ms']=Helper_Array::toHashmap(Mailtemplate::find()->getAll()->toArray(),'code');
    }
    
    function actionMailtemplatestatusmodify(){
        if(strlen($this->_context->code)){
            if(strlen($this->_context->id)<=0 && $this->_context->status){ //安装 
                $ss=Mailtemplate::find('code=?',$this->_context->code)->getOne();
                $s=Store_Mailtemplate::find('store_id=? And code=?',$this->store['store_id'],$this->_context->code)->getOne();
                if($s->isNewRecord()){
                    $s->store_id=$this->store['store_id'];
                    $s->code=$ss->code;
                    $s->name=$ss->name;
                    $s->title=$ss->title;
                    $s->content=$ss->content;
                }
                $s->status=$this->_context->status;
                $s->save();
                $this->_redirect(url('/Mailtemplates'));
            }
        }
        if(strlen($this->_context->id)){
            if(strlen($this->_context->status)){
                $s=Store_Mailtemplate::find('store_id=? And id=?',$this->store['store_id'],$this->_context->id)->getOne();
                $s->status=$this->_context->status;
                $s->save();
            }elseif($this->_context->cmd=='remove'){
                Store_Mailtemplate::meta()->deleteWhere('store_id=? And id=?',$this->store['store_id'],$this->_context->id);
            }
        }
        return $this->_redirect(url('/Mailtemplates'));
    }
    
    function actionMailtemplateEdit(){
        $id=$this->_context->query('id');
        
        $this->_view['ms']=Store_Mailtemplate::find('store_id=?',$this->store['store_id'])->getAll();
        $this->_view['m']=Store_Mailtemplate::find('store_id=? And id=?',$this->store['store_id'],$id)->getOne();
        if($this->_context->isPost()){
            do{
                if($this->_view['m']->isNewRecord()){
                    $this->_view['m']->store_id=$this->store['store_id'];
                }
                $this->_view['m']->name=$this->_context->post('name');
                $this->_view['m']->title=$this->_context->post('title');
                $this->_view['m']->content=$this->_context->post('content');
                $this->_view['m']->save();
                return $this->_redirect(url('/Mailtemplates'));
            }while(0);
        }
        if(isset($this->_view['m'])&&strlen($this->_view['m']->code)){
            $this->_view['sm']=Mailtemplate::find('code=?',$this->_view['m']->code)->getOne();
        }
    }
    
   //
    function actionLinks(){
        $links=Store_link::find('store_id=?',$this->store['store_id'])->order('sort')->getAll();
        if($this->_context->isPost()&&count($this->_context->post('sort'))){
            $sort=$this->_context->post('sort');
            
            foreach($links as $m){
                if(isset($sort[$m->id])&&strlen($sort[$m->id])){
                    $m->sort=(int)$sort[$m->id];
                    $m->save();
                }
            }
            return $this->_redirect(url('/links'));
        }
        $this->_view['links']=$links;
    }
    
    function actionLinkEdit(){
        $id=$this->_context->query('id');
        $this->_view['m']=Store_link::find('store_id=? And id=?',$this->store['store_id'],$id)->getOne();
        if($this->_context->isPost()&&strlen($this->_context->query('title'))){
            if($this->_view['m']->isNewRecord()){
                $this->_view['m']->store_id=$this->store['store_id'];
            }
            $this->_view['m']->type=$this->_context->query('type');
            $this->_view['m']->title=$this->_context->query('title');
            $this->_view['m']->url=$this->_context->query('url');
            $this->_view['m']->url2=$this->_context->query('url2');
            $this->_view['m']->status=$this->_context->query('status');
            $this->_view['m']->imgurl=$this->_context->query('imgurl');
            $this->_view['m']->save();
        
            return $this->_redirect(url('/links')); 
        }
    }
    
    function actionLinkRemove(){
        $id=$this->_context->query('id');
        Store_link::meta()->deleteWhere('store_id=? And id=?',$this->store['store_id'],$id);
        
        return $this->_redirect('storemanager/links');
    }
    /**
     * config s 
     */         
    function actionConfigs(){
        if($this->_context->isPost()){
            switch($this->_context->cmd){
                case 'reload':
                    $ss=Configs::find()->getAll();
                    foreach($ss as $s){
                        $c=Store_Configs::find('store_id=? And config_key=?',$this->store['store_id'],$s->config_key)->getOne();
                        $c->value=$s->value;
                        if($c->isNewRecord()){
                            $c->store_id=$this->store['store_id'];
                            $c->config_key=$s->config_key;
                        }
                        $c->save();
                    }
                default:
                    return $this->_redirect(url('/configs'));
                break;
            }
        }
        $this->_view['list']=Store_Configs::find('store_id=?',$this->store['store_id'])->getAll();
    }
    
    function actionConfigEdit(){
        $item=Store_Configs::find('store_id=? And id=?',$this->store['store_id'],$this->_context->id)->getOne();
        if($this->_context->isPost()){
            $item->value=$this->_context->post('value');
            $item->save();
            return $this->_redirect(url('/configs'));
        }
        $this->_view['m']=$item;
    }
}

